package cn.app.controller;

import cn.app.pojo.*;
import cn.app.service.App_categoryService;
import cn.app.service.App_infoService;
import cn.app.service.App_versionService;
import cn.app.service.Data_dictionaryService;
import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/app")
public class App_infoController {
    @Resource
    private App_infoService app_infoService;
    @Resource
    private Data_dictionaryService data_dictionaryService;
    @Resource
    private App_categoryService app_categoryService;
    @Resource
    private App_versionService app_versionService;

    @RequestMapping("/queryApp")
    public String queryApp(HttpServletRequest request, App_infoExt app_infoExt, String currentPageNo, String totalCount, String totalPageCount, String queryCategoryLevel1, String queryCategoryLevel2, String queryCategoryLevel3, String querySoftwareName, String queryStatus, String queryFlatformId) {
        if (querySoftwareName != null) {
            app_infoExt.setSoftwareName(querySoftwareName);
        }
        long staus = -1;
        if (queryStatus != null) {
            app_infoExt.setStatus(staus = Long.valueOf(queryStatus));
            System.out.println(staus);
        }
        long FlatformId = -1;
        if (queryFlatformId != null) {
            app_infoExt.setFlatformId(FlatformId = Long.valueOf(queryFlatformId));
        }
        int pageSize = 5;
        int currentPageno = 1;
        if (currentPageNo != null) {
            currentPageno = Integer.valueOf(currentPageNo);
        }
        long parentId1 = -1;
        if (queryCategoryLevel1 != null) {
            parentId1 = Long.valueOf(queryCategoryLevel1);
            app_infoExt.setCategoryLevel1(parentId1);
            System.out.println(parentId1);
        }
        long parentId2 = -1;
        if (queryCategoryLevel2 != null) {
            parentId2 = Long.valueOf(queryCategoryLevel2);
            app_infoExt.setCategoryLevel2(parentId2);
        }
        long parentId3 = -1;
        if (queryCategoryLevel3 != null) {
            parentId3 = Long.valueOf(queryCategoryLevel3);
            app_infoExt.setCategoryLevel3(parentId3);
        }
        List<Data_dictionary> statusList = data_dictionaryService.queryDic();
        List<Data_dictionary> flatFormList = data_dictionaryService.queryDicPt();
        List<App_category> categoryLevel1List = app_categoryService.queryCategory(null);
        List<App_category> categoryLevel2List = app_categoryService.queryCategory(parentId2);
        List<App_category> categoryLevel3List = app_categoryService.queryCategory(parentId3);

        HttpSession session = request.getSession();
        PageInfo<App_infoExt> pageInfo = app_infoService.queryApp(app_infoExt, currentPageno, pageSize);
        session.setAttribute("appInfoList", pageInfo.getList());
        session.setAttribute("currentPageNo", pageInfo.getPageNum());
        session.setAttribute("totalCount", pageInfo.getTotal());
        session.setAttribute("totalPageCount", pageInfo.getPages());
        session.setAttribute("app", app_infoExt);
        session.setAttribute("statusList", statusList);
        session.setAttribute("flatFormList", flatFormList);
        session.setAttribute("categoryLevel1List", categoryLevel1List);
        session.setAttribute("categoryLevel2List", categoryLevel2List);
        session.setAttribute("categoryLevel3List", categoryLevel3List);
        session.setAttribute("queryCategoryLevel1", parentId1);
        session.setAttribute("queryCategoryLevel2", parentId2);
        session.setAttribute("queryCategoryLevel3", parentId3);

        return "/developer/appinfolist";

    }

    @RequestMapping("/appAddjsp")
    public String addAppJsp() {
        return "developer/appinfoadd";
    }

    @RequestMapping("/addApp")
    public String addApp(App_info app_info, MultipartFile a_logoPicPath) {
        System.out.println(app_info);

        if (app_infoService.insertApp(app_info) > 0) {
            return "redirect:queryApp";
        }

        return "developer/appinfoadd";
    }

    @RequestMapping("/queryAPKName")
    public void queryAPKName(HttpServletResponse response, String APKName) throws IOException {
        List<App_info> appInfoList = app_infoService.queryAPKName();
        boolean f = true;
        if (appInfoList != null) {
            for (App_info a : appInfoList) {
                if (a.getAPKName().equals(APKName)) {
                    f = true;
                    break;
                } else {
                    f = false;
                }
            }
            if (f) {
                response.getWriter().print("true");
            } else if (f == false) {
                response.getWriter().print("false");
            } else if (StringUtils.isNullOrEmpty(APKName.trim())) {
                response.getWriter().print("empty");
            }

        }
    }

    @RequestMapping("/deleteApp")
    public void deleteApp(HttpServletResponse response, String id) throws IOException {
        int delapp = app_infoService.deleteByPrimaryKey(Long.valueOf(id));
        if (delapp > 0) {
            int delver = app_versionService.deleteByPrimaryKey(Long.valueOf(id));

                response.getWriter().print("true");

        } else {
            response.getWriter().print("false");
        }
    }

    @RequestMapping("/ByIdApp")
    public String ByIdApp(HttpServletRequest request, String id) {
        App_infoExt appInfo = app_infoService.selectByPrimaryKey(Long.valueOf(id));
        List<App_category> categoryLevel1List = app_categoryService.queryCategory(null);
        List<App_category> categoryLevel2List = app_categoryService.queryCategory(appInfo.getCategoryLevel1());
        List<App_category> categoryLevel3List = app_categoryService.queryCategory(appInfo.getCategoryLevel2());
        request.getSession().setAttribute("appInfo", appInfo);
        request.getSession().setAttribute("categoryLevel1List", categoryLevel1List);
        request.getSession().setAttribute("categoryLevel2List", categoryLevel2List);
        request.getSession().setAttribute("categoryLevel3List", categoryLevel3List);
        return "/developer/appinfomodify";
    }

    @RequestMapping("/updateApp")
    public String updateApp(App_info app_info) {
        if (app_info.getStatus()==3){
            app_info.setStatus(1L);
            int update = app_infoService.updateByPrimaryKey(app_info);
            if (update > 0) {
                return "redirect:queryApp";
            }  return "redirect:ByIdApp";
        }


        int update = app_infoService.updateByPrimaryKey(app_info);
        if (update > 0) {
            return "redirect:queryApp";
        }
        return "redirect:ByIdApp";
    }

    @RequestMapping("/showAppView")
    public String showAppView(HttpServletRequest request, String id) {
        App_infoExt appInfo = app_infoService.selectByPrimaryKey(Long.valueOf(id));
        List<App_versionExt> appVersionExtList = app_versionService.selectByPrimaryKey(Long.valueOf(id));
        request.getSession().setAttribute("appInfo", appInfo);
        request.getSession().setAttribute("appVersionExtList", appVersionExtList);
        return "developer/appinfoview";
    }

    @RequestMapping(value = "/saleChange")
    public String saleChange(String status,String id){
        App_info appInfo = new App_info();

        appInfo.setId(Long.valueOf(id));
        if (status.equals("2") || status.equals("5")){
            appInfo.setStatus(4L);
        }else if (status.equals("4")){
            appInfo.setStatus(5L);
        }
        app_infoService.updateAppStatus(appInfo);
        return "redirect:/app/queryApp";
    }
@RequestMapping("download")
public ResponseEntity<byte[]> download(String filePath, HttpServletRequest request) throws IOException {
    String downPath = request.getServletContext().getRealPath("/statics/uploadfiles");
    File file = new File(downPath + File.pathSeparator + filePath);
    byte[] b = null;
    if (file.exists()) {
        b = FileUtils.readFileToByteArray(file);
    }
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(filePath, "UTF-8"));
    httpHeaders.setContentLength(file.length());
    ResponseEntity responseEntity = new ResponseEntity(b, httpHeaders, HttpStatus.OK);
    return responseEntity;

}
    @RequestMapping("/delfile")
    public void delfile(HttpServletResponse response, String id,String logoPicPath) throws IOException {
        System.out.println(id);
        System.out.println(logoPicPath);
        int delfile=app_infoService.updateAppPic(logoPicPath,Long.valueOf(id));
        if (delfile>0){
            response.getWriter().print("true");
        }else {
            response.getWriter().print("false");
        }
    }

}
